<template>
  <div class="wrap">
    <pro-table
      ref="proTableInst"
      tableTitle="机构列表"
      :columns="columns"
      :request="fetchOrgPage"
      auto-height
    >
      <template #operation>
        <n-space>
          <n-button v-hasPermi="`org:add`" type="primary" @click="handleAddOrg">
            新增
          </n-button>
        </n-space>
      </template>
    </pro-table>

    <n-drawer
      v-model:show="orgDrawerShow"
      :width="500"
      resizable
      :maskClosable="false"
      @after-leave="resetOrgForm"
    >
      <n-drawer-content closable :title="handleTag">
        <pro-form
          ref="orgFormInst"
          v-model:form="orgForm"
          :options="orgFormOptions"
          :formProps="{
            labelPlacement: 'left',
            labelWidth: 120
          }"
        ></pro-form>

        <template #footer>
          <n-space>
            <n-button @click="orgDrawerShow = false">取消</n-button>
            <n-button
              type="primary"
              :loading="confirmLoading"
              @click="orgConfirm"
            >
              确认
            </n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script lang="ts" setup name="OrgList">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import { useOrgApi, useOrgProForm, useOrgProTable } from './hooks'
  import { OrgModel } from '@/api/model/org-model'

  const proTableInst = ref<ProTableInst | null>(null)
  const orgFormInst = ref<ProFormInst | null>(null)

  const orgDrawerShow = ref(false)
  const handleType = ref<'add' | 'edit' | ''>('')
  const handleTag = computed(() =>
    handleType.value === 'add' ? '新增机构' : '修改机构'
  )
  const { orgForm, resetOrgForm, orgFormOptions } = useOrgProForm()

  const handleAddOrg = () => {
    handleType.value = 'add'
    orgDrawerShow.value = true
  }

  const handleEditOrg = (row: OrgModel) => {
    orgForm.value = row
    handleType.value = 'edit'
    orgDrawerShow.value = true
  }

  const orgConfirm = async () => {
    if (await orgFormInst.value?.handleSubmit()) {
      fetchAddOrEditOrg()
    }
  }

  // 机构参数
  const router = useEncryptRouter()
  const handleEditOrgParam = (row) => {
    router.push({
      name: 'OrgParamList',
      query: { orgId: row.id, type: row.orgName }
    })
  }

  const { fetchOrgPage, fetchAddOrEditOrg, fetchDelOrg, confirmLoading } =
    useOrgApi({
      handleType,
      handleTag,
      orgDrawerShow,
      orgForm,
      proTableInst
    })
  const { columns } = useOrgProTable({
    handleEditOrg,
    fetchDelOrg,
    handleEditOrgParam
  })
</script>

<style lang="less" scoped></style>
